package com.common.widget.date;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TimePicker;

import com.common.R;

import java.util.Calendar;

import static android.media.CamcorderProfile.get;

/**
 * Created by wangxb on 2017/7/5.
 */
public class DatePickerDialogFragment extends DialogFragment implements DatePicker.OnDateChangedListener, TimePicker.OnTimeChangedListener, View.OnClickListener {
    
    private View mRootView;
    
    DatePicker mDatePicker;
    TimePicker mTimePicker;
    Button mSureBtn;
    
    private OnDateSetListener mOnDateSetListener;
    private int year;
    private int monthOfYear;
    private int dayOfMonth;
    private int hourOfDay;
    private int minute;
    
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mRootView = inflater.inflate(R.layout.date_picker_dialog, container);
        initView();
        return mRootView;
    }
    
    private void initView() {
        mDatePicker = (DatePicker) mRootView.findViewById(R.id.datePicker);
        mTimePicker = (TimePicker) mRootView.findViewById(R.id.timePicker);
        mSureBtn = (Button) mRootView.findViewById(R.id.pickerSure);
        
        Calendar cal = Calendar.getInstance();
        year = cal.get(Calendar.YEAR);
        monthOfYear = cal.get(Calendar.MONTH);
        dayOfMonth = cal.get(Calendar.DAY_OF_MONTH);
        hourOfDay = cal.get(Calendar.HOUR_OF_DAY);
        minute = cal.get(Calendar.MINUTE);
        
        
        mDatePicker.init(year, monthOfYear, dayOfMonth, this);
        
        mTimePicker.setOnTimeChangedListener(this);
        mSureBtn.setOnClickListener(this);
    }
    
    @Override
    public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
        this.year = year;
        this.monthOfYear = monthOfYear;
        this.dayOfMonth = dayOfMonth;
        
    }
    
    @Override
    public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
        this.hourOfDay = hourOfDay;
        this.minute = minute;
    }
    
    public OnDateSetListener getOnDateSetListener() {
        return mOnDateSetListener;
    }
    
    public void setOnDateSetListener(OnDateSetListener onDateSetListener) {
        mOnDateSetListener = onDateSetListener;
    }
    
    @Override
    public void onClick(View v) {
        if (mOnDateSetListener != null) {
            mOnDateSetListener.onDateSet(year, monthOfYear, dayOfMonth, hourOfDay, minute);
        }
        dismiss();
        
    }
    
    public interface OnDateSetListener {
        
        void onDateSet(int year, int monthOfYear, int dayOfMonth, int hourOfDay, int minute);
    }
}

